package cn.itcast.travel.web.servlet;

import cn.itcast.travel.domain.ResultInfo;
import cn.itcast.travel.domain.User;
import cn.itcast.travel.service.UserService;
import cn.itcast.travel.service.impl.UserServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * 实现user业务的功能的分发
 * 该类执行后没有service方法，会执行BaseServlet中的service方法
 *
 * @Author CHAI
 * @Date 2022/4/27 21:20
 **/
@WebServlet("/user/*")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    /**
     * 注册功能
     * */
    public void registerUserServlet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端输入的数据
        String check = request.getParameter("check");
        HttpSession session = request.getSession();

        String checkCode = (String) session.getAttribute("CHECKCODE_SERVER");
        //防止验证码进行重复使用
        session.removeAttribute("CHECKCODE_SERVER");
        if (!checkCode.equalsIgnoreCase(check)){
            //验证码输入错误
            ResultInfo resultInfo = new ResultInfo();
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("验证码输入有误");
            /*ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(resultInfo);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);*/
            //使用抽取方法
            writeValue(resultInfo,response);
            //结束该方法
            return;
        }
        //将数据封装为user对象(ajax发送的数据)
        Map<String, String[]> map = request.getParameterMap();
        User user = new User();
        try {
            //将map数据封装中user的数据中
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //UserService userService = new UserServiceImpl();
        boolean register = userService.register(user);
        //创建返回前端信息的对象
        ResultInfo resultInfo = new ResultInfo();
        if (register){
            //注册成功
            resultInfo.setFlag(true);
        }else{
            //注册失败
            resultInfo.setFlag(false);
            //存储失败信息、
            resultInfo.setErrorMsg("注册失败！");
        }
        /*ObjectMapper mapper = new ObjectMapper();
        //将返回信息的对象转化为json字符串
        String register_json = mapper.writeValueAsString(resultInfo);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(register_json);*/
        writeValue(resultInfo,response);
    }
    /**
     * 邮件的激活
     *
     * */
    public void activeUserServlet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求的激活码
        String code = request.getParameter("code");
        if (code==null){
            return;
        }
        //UserService userService = new UserServiceImpl();
        boolean flag=userService.active(code);
        String msg=null;
        if (flag){
            //激活成功
            msg="激活成功，请<a href='../login.html'>登录</a>";
        }else{
            //激活失败
            msg="激活失败！请联系管理员";
        }
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(msg);
    }
    /**
     * 登录的功能
     * */
    public void loginServlet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //验证码验证操作
        //获取前端输入的数据
        String check = request.getParameter("check");
        HttpSession session = request.getSession();

        String checkCode = (String) session.getAttribute("CHECKCODE_SERVER");
        //防止验证码进行重复使用
        session.removeAttribute("CHECKCODE_SERVER");
        if (!checkCode.equalsIgnoreCase(check)){
            //验证码输入错误
            ResultInfo resultInfo = new ResultInfo();
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("验证码输入有误");
            /*ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(resultInfo);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);*/
            writeValue(resultInfo,response);
            //结束该方法
            return;
        }
        //获取登录信息的集合
        Map<String, String[]> map = request.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //UserService userService = new UserServiceImpl();
        User u=userService.login(user);
        ResultInfo resultInfo = new ResultInfo();
        //用户为null，登录失败
        if (u==null){
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("该账号还没有注册，请先注册");
        }
        //用户的激活状态不是Y
        if (u!=null&& !"Y".equals(u.getStatus())){
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("账号尚未激活，请先激活");
        }
        //激活成功
        if (u!=null && "Y".equals(u.getStatus())){
            resultInfo.setFlag(true);
            //将用户的信息存储session中用于用户信息的展示
            session.setAttribute("login_msg",u);
        }
        /*ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(resultInfo);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);*/
        writeValue(resultInfo,response);
    }
    /**
     * 登录名称的显示
     *
     * */
    public void findUserServlet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("login_msg");
        /*ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(user);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);*/
        writeValue(user,response);
    }
    /**
     * 退出功能的显示
     * */
    public void exitServlet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //销毁session
        request.getSession().invalidate();
        //跳转到登录界面
        response.sendRedirect(request.getContextPath()+"/login.html");
    }
}
